package com.mingqijia.gassafety.webserver.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gap.basic.exception.BizException;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.mingqijia.gassafety.db.entity.Consumer;
import com.mingqijia.gassafety.db.entity.CustomerSubs;
import com.mingqijia.gassafety.db.entity.CustomerSubsHistory;
import com.mingqijia.gassafety.db.mapper.ConsumerMapper;
import com.mingqijia.gassafety.db.mapper.CustomerSubsHistoryMapper;
import com.mingqijia.gassafety.db.mapper.CustomerSubsMapper;
import com.mingqijia.gassafety.shared.constant.Constants;
import com.mingqijia.gassafety.shared.utils.ApplicationUtils;
import com.mingqijia.gassafety.shared.utils.commonUtils.BeanConvertUtils;
import com.mingqijia.gassafety.shared.utils.commonUtils.PageUtil;
import com.mingqijia.gassafety.webserver.request.CustomerSubsHistoryRequest;
import com.mingqijia.gassafety.webserver.request.client.BindSubsRequest;
import com.mingqijia.gassafety.webserver.request.client.ClientDtuListRequest;
import com.mingqijia.gassafety.webserver.response.CustomerSubsHistoryResponse;
import com.mingqijia.gassafety.webserver.service.CompanyService;
import com.mingqijia.gassafety.webserver.service.CustomerSubsHistoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.Arrays;
import java.util.List;

/**
 * <p>
 *
 * @author wanghai
 * @since 2022-06-21
 */

@Service
@Slf4j
public class CustomerSubsHistoryServiceImpl extends ServiceImpl<CustomerSubsHistoryMapper, CustomerSubsHistory> implements CustomerSubsHistoryService {

    @Autowired
    private CustomerSubsMapper customerSubsMapper;

    @Autowired
    private CustomerSubsHistoryMapper customerSubsHistoryMapper;

    @Autowired
    private ConsumerMapper consumerMapper;

    @Autowired
    private CompanyService companyService;

    @Autowired
    private CustomerSubsHistoryService customerSubsHistoryService;

    @Value(value = "${h5.useOpenIdBindSubs.orgIds:}")
    private String useOpenIdBindSubsOrgIds;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String bindSubs(BindSubsRequest request) {
        log.info("bindSubs-param:{}", JSONObject.toJSON(request));
        //将 orgCode换spId
        String spId = companyService.getSpId( request.getOrgCode() );
        //判断户号是否存在
        QueryWrapper<Consumer> consumerQueryWrapper = new QueryWrapper<>();
        consumerQueryWrapper.lambda().eq( Consumer::getSubsCode,request.getSubsCode() )
                .eq( Consumer::getIsDeleted,Constants.IS_DELETED_FALSE )
                .eq(Consumer::getSpId, spId);
        List<Consumer> consumerList = consumerMapper.selectList( consumerQueryWrapper );
        if (CollectionUtil.isEmpty( consumerList )){
            //户号不存在
            throw new BizException( "该户号并未创建客户无法进行绑定" );
        }
        log.info("bindSubs-consumerList:{}", JSONObject.toJSON(consumerList));
        
        boolean isSpecial = isUseOpenIdBindSubsOrgId(request.getOrgId());
        //判断重复绑定
        LambdaQueryWrapper<CustomerSubs> subsQueryWrapper = new LambdaQueryWrapper<>();
        subsQueryWrapper.eq( CustomerSubs::getPhone,request.getPhone() );
        if( isSpecial ){
            subsQueryWrapper.eq(CustomerSubs::getVccUserId, request.getVccUserId());
        }else {
            subsQueryWrapper.eq(CustomerSubs::getSubsCode, request.getSubsCode());
        }
        subsQueryWrapper.eq( CustomerSubs::getBandingStatus, 1 )
                .eq( CustomerSubs::getIsDeleted, Constants.IS_DELETED_FALSE )
                .eq( CustomerSubs::getSpId,spId );
        List<CustomerSubs> customerSubsList = customerSubsMapper.selectList( subsQueryWrapper );
        if (CollectionUtil.isNotEmpty( customerSubsList )){
            log.info( "用户:{},户号:{}已经绑定",request.getPhone(), request.getSubsCode() );
            return "请勿重复绑定户号";
        }
        //绑定
        CustomerSubs customerSubs = new CustomerSubs();
        customerSubs.setBandingStatus( 1 );
        if( isSpecial ){
            customerSubs.setVccUserId(request.getVccUserId());
        }else {
            customerSubs.setPhone(request.getPhone());
        }
        customerSubs.setSubsCode( request.getSubsCode() );
        customerSubs.setSpId( spId );
        customerSubsMapper.insert( customerSubs );
        //新增绑定记录
        CustomerSubsHistory history = new CustomerSubsHistory();
        history.setEvent( 1 ); //绑定
        if( isSpecial ){
            history.setVccUserId( request.getVccUserId() );
        }else{
            history.setPhone( request.getPhone() );
        }
        history.setSubsCode( request.getSubsCode() );
        history.setChannel( "H5" );
        history.setSpId( spId );
        log.info("bindSubs-history:{}", JSONObject.toJSON(consumerList));
        customerSubsHistoryMapper.insert( history );
        return "success";

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String unbindSubs(BindSubsRequest request) {
        log.info("unbindSubs-param:{}", JSONObject.toJSON(request));
        String orgCode = companyService.getOrgCodeBySpId(request.getOrgCode());
        //将 orgCode换spId
        String spId = companyService.getSpId( orgCode );
        //判断户号是否存在 客户表
        QueryWrapper<Consumer> consumerQueryWrapper = new QueryWrapper<>();
        consumerQueryWrapper.lambda().eq( Consumer::getSubsCode,request.getSubsCode() )
                .eq( Consumer::getIsDeleted,Constants.IS_DELETED_FALSE )
                .eq( Consumer::getSpId,spId );
        List<Consumer> consumerList = consumerMapper.selectList( consumerQueryWrapper );
        if (consumerList.isEmpty()){
            log.info( "户号:"+request.getSubsCode()+" 并未创建客户" );
            return "户号:"+request.getSubsCode()+" 并未创建客户";
        }
        boolean isSpecial = isUseOpenIdBindSubsOrgId(request.getOrgId());
        //解绑,特殊情况 解绑的户号并未绑定客户
        //从没存过绑定关系,  和已经解绑有记录
        LambdaQueryWrapper<CustomerSubs> subsQueryWrapper = new LambdaQueryWrapper<>();
        subsQueryWrapper.eq( CustomerSubs::getPhone, request.getPhone() );
        
        if( isSpecial ){
            subsQueryWrapper.eq(CustomerSubs::getVccUserId, request.getVccUserId());
        }else {
            subsQueryWrapper.eq(CustomerSubs::getSubsCode, request.getSubsCode());
        }
        
        subsQueryWrapper.eq( CustomerSubs::getIsDeleted, Constants.IS_DELETED_FALSE )
                .eq( CustomerSubs::getSpId, spId );
        CustomerSubs customerSubs = new CustomerSubs();
        customerSubs.setBandingStatus( 0 );
        List<CustomerSubs> subsList = customerSubsMapper.selectList( subsQueryWrapper );
        if (subsList.isEmpty()){
            log.info( "户号:"+request.getSubsCode()+" 并未绑定过客户" );
            return "户号:"+request.getSubsCode()+" 并未绑定过客户";
        }
        subsQueryWrapper.eq( CustomerSubs::getBandingStatus, 1 ); //绑定状态
        //重复解绑, 该户号手机号没有绑定数据
        List<CustomerSubs> bindSubsList = customerSubsMapper.selectList( subsQueryWrapper );
        if (bindSubsList.isEmpty()){
            log.info("户号:"+request.getSubsCode()+" 请勿重复解绑");
            return "户号:"+request.getSubsCode()+" 请勿重复解绑";
        }
        customerSubsMapper.update(customerSubs, subsQueryWrapper );

        //新增解绑记录
        CustomerSubsHistory history = new CustomerSubsHistory();
        history.setSpId( "0" );
        history.setSubsCode( request.getSubsCode() );
        if( isSpecial ){
            history.setVccUserId( request.getVccUserId() );
        }else{
            history.setPhone( request.getPhone() );
        }
        history.setEvent( 0 );
        history.setChannel( "H5" );
        int insert = customerSubsHistoryMapper.insert( history );
        return "success";
    }

    @Override
    public PageUtil<CustomerSubsHistoryResponse> getListBySubs(CustomerSubsHistoryRequest request) {
        String spId = ApplicationUtils.getWorkingSpId();
        Page<CustomerSubsHistory> page = PageHelper.startPage( request.getPage(), request.getPageSize() );
        QueryWrapper<CustomerSubsHistory> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq( CustomerSubsHistory::getSubsCode,request.getSubsCode() )
                .eq( CustomerSubsHistory::getIsDeleted, Constants.IS_DELETED_FALSE )
                .eq( CustomerSubsHistory::getSpId , spId);
        List<CustomerSubsHistory> list = customerSubsHistoryMapper.selectList( queryWrapper );
        List<CustomerSubsHistoryResponse> responseList = BeanConvertUtils.convertListTo( list, CustomerSubsHistoryResponse::new );
        PageUtil<CustomerSubsHistoryResponse> pageUtil = new PageUtil<>();
        pageUtil.setTotal( page.getTotal() );
        pageUtil.setPage( request.getPage() );
        pageUtil.setPageSize( request.getPageSize() );
        pageUtil.setList( responseList );
        return pageUtil;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void isBindSus( ClientDtuListRequest request, String spId) {
        // 查询该 用户和户号是否绑定
        LambdaQueryWrapper<CustomerSubs> subsQueryWrapper = new LambdaQueryWrapper<>();
        boolean isSpecial = isUseOpenIdBindSubsOrgId(request.getOrgId());
       subsQueryWrapper.eq( CustomerSubs::getSubsCode,request.getSubsCode())
                .eq( CustomerSubs::getIsDeleted, Constants.IS_DELETED_FALSE )
                .eq( CustomerSubs::getSpId,spId );
        if( isSpecial ){
            subsQueryWrapper.eq( CustomerSubs::getVccUserId, request.getVccUserId() );
        }else{
            subsQueryWrapper.eq( CustomerSubs::getPhone, request.getPhone()); 
        }
        
        List<CustomerSubs> userSubsList = customerSubsMapper.selectList( subsQueryWrapper );
        if (CollectionUtil.isEmpty( userSubsList )){
            BindSubsRequest bindSubsRequest = new BindSubsRequest();
            if( isSpecial ){
                bindSubsRequest.setVccUserId( request.getVccUserId() );
            }else{
                bindSubsRequest.setPhone( request.getPhone() );
            }
            bindSubsRequest.setSubsCode( request.getSubsCode() );
            bindSubsRequest.setOrgCode( request.getOrgCode() );
            bindSubsRequest.setOrgId( request.getOrgId() );
            customerSubsHistoryService.bindSubs( bindSubsRequest );
            log.info( "用户:{} 和 户号:{}存在绑定关系,已经自动绑定",request.getPhone(), request.getSubsCode() );
        }
    }

    @Override
    public void checkH5Request(String orgId , String phone,  String vccUserId) {
        if( isUseOpenIdBindSubsOrgId(orgId) ){
            if( StringUtils.isEmpty(vccUserId) ){
                throw new BizException("VCC用户id不能为空");
            }
        }else if( StringUtils.isEmpty(phone) ){
            throw new BizException("用户手机号不能为空");
        }
    }

    @Override
    public boolean isUseOpenIdBindSubsOrgId(String orgId) {
        try {
            if (StringUtils.isEmpty(orgId)) {
                return false;
            }
            if (!StringUtils.isEmpty(useOpenIdBindSubsOrgIds)) {
                List<String> orgIds = Arrays.asList(useOpenIdBindSubsOrgIds.split(","));
                return orgIds.contains(orgId);
            }
        }catch (Exception e){
            log.error("判断h5绑定户号是否使用微信openid出错",e);
        }
        return false;
    }
}
